package com.gzw.dms.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.BuildConfig;
import com.gzw.dms.KJ.*;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.BackOrderInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.DateUtil;
import com.gzw.dms.utils.FileUtil;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.ToolFor9Ge;
import com.gzw.dms.utils.UrlUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StorageUtils;

public class BackjdDetailActivity extends BaseActivity {
    private Context mContext;
    private DatePickerDialog dpd;
    private ProgressDialog mProgressDialog;
    private String costomersid,user_id;
    private String shiping_order_num;
    private Button btn_sign;
    private Intent mIntent;
    private Toolbar toolbar;
    private EditText et_custom_tel,et_receipt_name,et_sign_receipt_tel,et_sign_goodsName,et_end_dress,
            et_custom_name,et_sign_remarks,et_sign_goodsrealnum,et_order_num,et_receipt,et_custom;
    private TextView tv_send_mechanism,et_sign_endadress,et_end_mechanism,et_sign_startdress,et_shopping_order_goid,
            et_time,et_remarks_order,et_sign_goodsNumber,tv_type,et_sign_goodsWeight,et_sign_goodsVol;
    private BackOrderInfo info;
    private String  type = "0";
    private LinearLayout layout_type;
    private BackOrderInfo shippingOrder;
    private int imgH = 800;
    private int imgW = 600;
    private ImageView iv_uploading;
    private String isUploadPhotos = "0";
    private  String fileRoot = "takingReverseOrder";
    private String path;
    private int REQUEST_CODE_CAMERA=1;
    private String fileName1;
    private LinearLayout layout_remarks;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initConfig();
        init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_backjd_detail);

    }

    @Override
    protected void initViews() {

        btn_sign = ((Button) findViewById(R.id.btn_sign));
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        iv_uploading = ((ImageView) findViewById(R.id.iv_uploading));

        et_order_num = ((EditText) findViewById(R.id.et_order_num));
        et_shopping_order_goid = ((EditText) findViewById(R.id.et_shopping_order_goid));

//        et_sign_startdress = ((TextView) findViewById(R.id.et_sign_startdress));
        et_sign_endadress = ((TextView) findViewById(R.id.et_sign_endadress));
        et_custom_name = ((EditText) findViewById(R.id.et_custom_name));
        et_custom = ((EditText) findViewById(R.id.et_custom));
        et_time = ((TextView) findViewById(R.id.et_time));
        et_sign_goodsName = ((EditText) findViewById(R.id.et_sign_goodsName));
        et_custom_tel = ((EditText) findViewById(R.id.et_custom_tel));
        et_sign_goodsNumber = ((TextView) findViewById(R.id.et_sign_goodsNumber));
        et_sign_goodsWeight = ((TextView) findViewById(R.id.et_sign_goodsWeight));
        et_sign_goodsVol = ((TextView) findViewById(R.id.et_sign_goodsVol));
        et_sign_goodsrealnum = ((EditText) findViewById(R.id.et_sign_goodsrealnum));
        et_sign_remarks = ((EditText) findViewById(R.id.et_sign_remark));
        et_receipt_name = ((EditText) findViewById(R.id.et_receipt_name));
        et_receipt = ((EditText) findViewById(R.id.et_receipt));
        et_sign_receipt_tel = ((EditText) findViewById(R.id.et_sign_receipt_tel));
        et_end_mechanism = (TextView) findViewById(R.id.et_end_mechanism);
        tv_send_mechanism = (TextView) findViewById(R.id.tv_send_mechanism);
        tv_type = ((TextView) findViewById(R.id.tv_type));
        layout_type = (LinearLayout) findViewById(R.id.layout_type);
        et_remarks_order = ((TextView) findViewById(R.id.et_remarks_order));
        layout_remarks = (LinearLayout) findViewById(R.id.layout_remarks);
        et_end_dress = ((EditText) findViewById(R.id.et_end_dress));

    }

    @Override
    protected void initData() {

        readUserContent();
        mContext = this;
        toolbar.setTitle("提货");
        layout_type.setVisibility(View.GONE);
        mIntent = getIntent();

        shippingOrder = (BackOrderInfo) mIntent.getExtras().get(
                "shippingOrder");

        setData(shippingOrder);
    }



    @Override
    protected void initEvents() {
        btn_sign.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());
//        tv_send_mechanism.setOnClickListener(new myOnClick());
//        et_sign_endadress.setOnClickListener(new myOnClick());
        et_end_mechanism.setOnClickListener(new myOnClick());
        iv_uploading.setOnClickListener(new myOnClick());

    }

    private void setData(BackOrderInfo shippingOrderInfo) {

        et_order_num.setText(shippingOrderInfo.getShiping_order_num());
        et_shopping_order_goid.setText(shippingOrderInfo.getShiping_order_goid());

//        et_sign_startdress.setText(shippingOrderInfo.getSend_station());
        et_sign_endadress.setText(shippingOrderInfo.getEnd_address());
        tv_send_mechanism.setText(shippingOrderInfo.getSend_mechanism());

        et_custom_name.setText(shippingOrderInfo.getCustom_name());
        et_custom.setText(shippingOrderInfo.getCustom_contact());
        et_time.setText(shippingOrderInfo.getTime_limitation());
        et_custom_tel.setText(shippingOrderInfo.getCustom_tel());

        et_sign_goodsName.setText( shippingOrderInfo.getGoods_name());
        if (shippingOrderInfo.getOrder_type()==0){
            tv_type.setText("退货");
            layout_type.setVisibility(View.GONE);
        }else {
            tv_type.setText("调拨");
            layout_type.setVisibility(View.VISIBLE);
            et_receipt_name.setText(shippingOrderInfo.getReceipt_name());
            et_receipt.setText( shippingOrderInfo.getReceipt_contact());
            et_sign_receipt_tel.setText(shippingOrderInfo.getReceipt_tel());
            et_end_mechanism.setText(shippingOrderInfo.getEnd_mechanism());
            et_end_dress.setText(shippingOrderInfo.getReceipt_address());

        }
        et_sign_goodsNumber.setText(shippingOrderInfo.getGoods_num());
        et_sign_goodsrealnum.setText(shippingOrderInfo.getGoods_num());
        et_sign_goodsVol.setText(shippingOrderInfo.getGoods_vol());
        et_sign_goodsWeight.setText(shippingOrderInfo.getGoods_weight());

        et_sign_remarks.setText(shippingOrderInfo.getRemarks());
        String flag = MyApplication.getUserInfo().getFlag();
        if (flag.equals("3")||flag.equals("4")||flag.equals("0")){
            et_remarks_order.setText(shippingOrderInfo.getRemarks_order());
        }else {
            layout_remarks.setVisibility(View.GONE);
        }
        //订单状态

    }
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;

                case R.id.tv_send_mechanism:
                    Intent mIntent = new Intent();
                    mIntent.putExtra("type", "1");
                    mIntent.setClass(mContext, com.gzw.dms.KJ.SelectCustomerActivity.class);
                    startActivityForResult(mIntent, 0);
                    break;
                case R.id.et_end_mechanism:
                    Intent mIntent1 = new Intent();
                    mIntent1.putExtra("who", "0");
                    mIntent1.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent1, 2);
                    break;
                case R.id.et_sign_endadress:
                    Intent mIntent2 = new Intent();
                    mIntent2.putExtra("who", "1");
                    mIntent2.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent2, 3);
                    break;

                case R.id.iv_uploading:
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            path = resultList.get(0).getPhotoPath().toString();
                            DisplayImageOptions options = new DisplayImageOptions.Builder()
                                    .showImageOnFail(R.drawable.ic_gf_default_photo)
                                    .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                                    .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file:/" + path, iv_uploading, options);

                            if (!isNull(path)) {
                                fileName1 = shippingOrder.getShiping_order_num().trim() + "--" + DateUtil.getFileName();
                                uploadPhotos(path, fileName1);

                            }
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {
                            T.showShort(getApplicationContext(), errorMsg);
                            Log.e("onHanlderFailure", "");
                        }
                    });
                    break;

                default:
                    finish();
                    break;
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 3){
            try {
                String name = data.getStringExtra("name");
                costomersid = data.getStringExtra("id");
                tv_send_mechanism.setText(name);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 4){

            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                String str = province+city+county.substring(1,county.length()-1);
                et_sign_endadress.setText(str);
            } catch (Exception e) {
                // TODO: handle exception
            }
        } else if (resultCode == 2){
            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                String str = province+city+county.substring(1,county.length()-1);
                et_end_mechanism.setText(str);
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    }

    public void SaveHttpClientPost() {
//        if (isNull(tv_order_number)) {
//            T.showShort(mContext, "订单号不能为空");
//            return;
//        }
//
//        if (isNull(et_order_num)) {
//            T.showShort(mContext, "货运编号不能为空");
//            return;
//        }
//        if (isNull(et_sign_startdress)) {
//            T.showShort(mContext, "起运地不能为空");
//            return;
//        }
//        if (isNull(et_sign_endadress)) {
//            T.showShort(mContext, "终到位置不能为空");
//            return;
//        }
//        if (isNull(et_custom_name)) {
//            T.showShort(mContext, "发货客户名称不能为空");
//            return;
//        }
//
//        if (isNull(et_custom_tel)) {
//            T.showShort(mContext, "发货客户电话不能为空");
//            return;
//        }
//        if (isNull(et_sign_goodsName)) {
//            T.showShort(mContext, "货物名称不能为空");
//            return;
//        }
//
//        if (isNull(et_sign_goodsNumber)) {
//            T.showShort(mContext, "货物数量不能为空");
//            return;
//        }
//        if (isNull(et_sign_goodsrealnum)) {
//            T.showShort(mContext, "货物实际数量不能为空");
//            return;
//        }
//        if (isNull(et_time)) {
//            T.showShort(mContext, "提货时效不能为空");
//            return;
//        }
//        if (isNull(tv_send_mechanism)) {
//            T.showShort(mContext, "受理机构不能为空");
//            return;
//        }
        isUploadPhotos = FileUtil.getInstance().isUpload();
        if (isUploadPhotos=="0") {
            T.showShort(mContext, "请上传图片");
            return;
        }else if(isUploadPhotos=="1"){
            T.showShort(mContext, "请等待图片上传");
            return;
        }
        if (shippingOrder == null){
            shippingOrder = new BackOrderInfo();}
        shippingOrder.setOrder_type(shippingOrder.getOrder_type());
        shippingOrder.setTime_limitation(et_time.getText().toString());
        shippingOrder.setShiping_order_num(et_order_num.getText().toString().trim());
        shippingOrder.setShiping_order_goid(et_shopping_order_goid.getText().toString().trim());
//        shippingOrder.setSend_station(et_sign_startdress.getText().toString().trim());
        shippingOrder.setCustom_tel(et_custom_tel.getText().toString().trim());
        shippingOrder.setEnd_mechanism(et_sign_endadress.getText().toString().trim());
        shippingOrder.setCustom_name(et_custom_name.getText().toString().trim());
        shippingOrder.setCustom_contact(et_custom.getText().toString().trim());
        shippingOrder.setSend_mechanism(tv_send_mechanism.getText().toString().trim());
        shippingOrder.setGoods_name(et_sign_goodsName.getText().toString().trim());
        shippingOrder.setGoods_weight(et_sign_goodsWeight.getText().toString().trim());
        shippingOrder.setGoods_vol(et_sign_goodsVol.getText().toString().trim());
        shippingOrder.setGoods_num(et_sign_goodsNumber.getText().toString().trim());
        shippingOrder.setReal_num(et_sign_goodsrealnum.getText().toString().trim());
        shippingOrder.setRemarks(et_sign_remarks.getText().toString().trim());
        shippingOrder.setRemarks_order(et_remarks_order.getText().toString().trim());

        int order_type = shippingOrder.getOrder_type();
        if (order_type==0){
            shippingOrder.setOrder_type(order_type);
        }else {
            shippingOrder.setOrder_type(order_type);
            shippingOrder.setReceipt_name(et_receipt_name.getText().toString().trim());
            shippingOrder.setReceipt_tel(et_sign_receipt_tel.getText().toString().trim());
            shippingOrder.setReceipt_contact(et_receipt.getText().toString().trim());
            shippingOrder.setEnd_mechanism(et_end_mechanism.getText().toString().trim());
            shippingOrder.setReceipt_address(et_end_dress.getText().toString().trim());

        }
        shippingOrder.setOrder_type(order_type);

        SignShipOrder signShipOrder = new SignShipOrder();
        signShipOrder.execute(shippingOrder);
    }

    public class SignShipOrder extends AsyncTask<BackOrderInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(BackOrderInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("reverseOrderInfo", params[0]);
            map.put("newFileName", fileName1);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appSaveTakingReturnGoods"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    FileUtil.getInstance().noUpload();
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }
    }

    private void readUserContent() {


    }
    private void uploadPhotos(String path, String fileName){

        Bitmap bitmap = null;
        File file = new File(path);
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                bitmap = BitmapFactory.decodeStream(fis);
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (bitmap!=null) {
//                newFileName = shippingOrder.getShiping_order_num()+"--"+DateUtil.getFileName();
                bitmap = ToolFor9Ge.zoomImg(bitmap, imgW, imgH);
                FileUtil.getInstance().uploadFile(bitmap, fileName,fileRoot);
            }
            if(bitmap.isRecycled()==false) //如果没有回收
                bitmap.recycle();
        }
    }


    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()

                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setDebug(BuildConfig.DEBUG)
                .setFunctionConfig(functionConfig)

                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }

}
